///Users/liqiang/Desktop/demo/lib/QLCustomCamera/Example/QLCustomCamera/ControllerView
//  QLPhotoViewController.m
//  QLCustomCamera_Example
//
//  Created by 李强 on 2020/8/29.s

#import "QLPhotoViewController.h"
#import "QLTopPhotoView.h"
#import "QLSettingView.h"
#import "QLTimeVIew.h"
#import "QLRecordView.h"
#import "QLBottomOptionsView.h"
#import "QLRecordParam.h"
#import "QLRecordManager.h"
#import <objc/runtime.h>
#import "QLFilterView.h"
#import "QLVideoPlayer.h"
#import "TZImagePickerController.h"
#import "QLConfigure.h"
#import "UIImage+QLImage.h"


@interface QLPhotoViewController ()<QLRecordManagerVCDelegate,QLTopOptionsViewDelegate,QLRecordViewDelegate,QLFilterViewDelegate,QLBottomOptionDelegate,QLSettingViewDelegate,TZImagePickerControllerDelegate>


@property (nonatomic,strong)QLTopPhotoView *topView;//顶部view
@property (nonatomic,strong)QLSettingView *settingView;//设置页面
//@property (nonatomic,strong)QLTimeVIew *recordTimeView;//录制时间view
@property (nonatomic,strong)QLRecordView *recordView;//录制view
@property (nonatomic,strong)QLBottomOptionsView *optionsView;//底部选项View

@property (nonatomic,strong)QLFilterView *filterView;//滤镜界面
@property (nonatomic,strong)QLRecordParam *param;//录制参数
@property (nonatomic,strong)QLVideoPlayer *playerVC;
@property (nonatomic,strong)NSURL *outputFileUrl;//视频输出路径


@property (nonatomic,assign)NSInteger currentFilterIndex;
@property (nonatomic,assign)NSInteger flag;//标记


@end

@implementation QLPhotoViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    self.navigationController.navigationBarHidden=YES;
#pragma clang diagnostic pop
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    self.navigationController.navigationBarHidden=NO;
#pragma clang diagnostic pop
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self checkCameraStatus];
}

-(void)initData
{
    self.flag = 0;
    self.param = [QLRecordManager shareManager].recordParam;
}
//MARK:-----配置页面--------
-(void)configureView
{
    self.topView = [[QLTopPhotoView alloc]initWithFrame:CGRectMake(0, QL_SAFEAREA_TOP_HEIGH-QL_STATUS_HEIGHT/2, QL_SCREEN_WIDTH, 40)];
    self.topView.delegate = self;
    self.topView.beautyBtn.hidden = !self.param.isShowBeautyBtn;
    [self.view addSubview:self.topView];
    
//    //录制时间
//    self.recordTimeView = [[QLTimeVIew alloc]initWithFrame:CGRectMake(0, 0, QL_SCREEN_WIDTH, 35+QL_SAFEAREA_TOP_HEIGH-20)];
//    self.recordTimeView.hidden = !self.topView.hidden;
//    [self.view addSubview:self.recordTimeView];
    
    //录制view
    CGFloat recordHeight = QL_TIMEVIEW_HEIGHT+QL_STARTBTN_WIDTH+QL_MARGIN*2.0;
    CGFloat y = QL_SCREEN_HEIGHT - QL_SAFEAREA_BOTTOM_HEIGH - recordHeight;
    self.recordView = [[QLRecordView alloc]initWithFrame:CGRectMake(0, y, QL_SCREEN_WIDTH, recordHeight)];
    self.recordView.delegate = self;
    [self.view addSubview:self.recordView];
 
    
    
    //底部按钮及切换
    self.optionsView = [[QLBottomOptionsView alloc]initWithFrame:CGRectMake(0, QL_SCREEN_HEIGHT-QL_SAFEAREA_BOTTOM_HEIGH - (QL_STARTBTN_WIDTH + QL_MARGIN*2.0), QL_SCREEN_WIDTH, QL_STARTBTN_WIDTH)];
    self.optionsView.hidden = YES;
    self.optionsView.delegate = self;
    [self.view addSubview:self.optionsView];
    
}
//MARK:----------准备录制/录制结束
//准备录制
-(void)readyRecordVideo
{
    [QLRecordManager shareManager].vcDelegate = self;
    self.param.isBeauty = self.topView.beautyBtn.selected;
    [[QLRecordManager shareManager] configVideoParamsWithRecordParam:self.param];
}
//录制结束
-(void)recordFinished
{
    [[QLRecordManager shareManager] endRecord];
    objc_setAssociatedObject(self.topView.lightBtn, @"light_state", @"record_light_off", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self.topView.lightBtn setImage:[UIImage getBundleImageWithName:@"record_light_off" className:NSStringFromClass([self class])] forState:UIControlStateNormal];
    [[QLRecordManager shareManager]changeLightWithState:AVCaptureTorchModeOff];
}



//MARK:-------QLTopOptionsViewDelegate---------
//关闭
-(void)close
{
    [self recordFinished];
    //改滤镜
    [[QLRecordManager shareManager] changeFilter:[GPUImageFilter new]];
    //停止重力
    [[QLRecordManager shareManager] stopDeviceMotionUpdates];
    [self dismissViewControllerAnimated:YES completion:nil];
}
//切换镜头
-(void)turnCamera:(UIButton *)sender
{
    sender.enabled = NO;
    [[QLRecordManager shareManager] turnCamera];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.3*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sender.enabled = YES;
    });
}
//闪光灯
-(void)light:(UIButton *)sender
{
    NSString *state = objc_getAssociatedObject(sender, "light_state");
    if ([state isEqualToString:@"record_light_off"]) {
        objc_setAssociatedObject(sender, "light_state", @"record_light_on", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [sender setImage:[UIImage getBundleImageWithName:@"record_light_on" className:NSStringFromClass([self class])] forState:UIControlStateNormal];
        [[QLRecordManager shareManager] changeLightWithState:AVCaptureTorchModeOn];
    }else if ([state isEqualToString:@"record_light_on"]){
        objc_setAssociatedObject(sender, "light_state", @"record_light_auto", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [sender setImage:[UIImage getBundleImageWithName:@"record_light_auto" className:NSStringFromClass([self class])] forState:UIControlStateNormal];
        [[QLRecordManager shareManager]changeLightWithState:AVCaptureTorchModeAuto];
    }else{
        objc_setAssociatedObject(sender, "light_state", @"record_light_off", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [sender setImage:[UIImage getBundleImageWithName:@"record_light_off" className:NSStringFromClass([self class])] forState:UIControlStateNormal];
        [[QLRecordManager shareManager]changeLightWithState:AVCaptureTorchModeOff];
    }
}
//美颜
-(void)beauty:(UIButton *)sender
{
    sender.selected = !sender.selected;
    [[QLRecordManager shareManager]isOpenBeauty:sender.selected];
}

//MARK:-------QLRecordViewDelegate--------
//更新界面
-(void)updateViewWithOptionsViewHidden:(BOOL)isHidden
{
    self.optionsView.hidden = isHidden;
    self.recordView.hidden = !self.optionsView.hidden;
//    self.recordTimeView.hidden = self.recordView;
    if (self.param.getCurrentMode == videoMode) {
        self.topView.hidden = [QLRecordManager shareManager].isRecording;
    }else{
        self.topView.hidden = !self.optionsView.hidden;
    }
}
//显示滤镜界面
-(void)showFilterView
{
    self.recordView.hidden = YES;
    QLFilterView *filterView = [[QLFilterView alloc]initWithFrame:CGRectMake(0, QL_SCREEN_HEIGHT - QL_SAFEAREA_BOTTOM_HEIGH - 120, QL_SCREEN_WIDTH, 120)];
    self.filterView = filterView;
    filterView.viewStyle = blackViewStyle;
    filterView.currentFilterIndex = self.currentFilterIndex;
    filterView.delegate = self;
    [self.view addSubview:filterView];
}

-(void)showAlbum
{
    TZImagePickerController *pickerVC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    pickerVC.allowTakePicture = NO;
    pickerVC.allowPickingVideo = NO;
    pickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:pickerVC animated:YES completion:nil];
}

//MARK:---------QLFilterViewDelegate----------
-(void)changeFilter:(GPUImageFilter *)filter currentFilterIndex:(NSInteger)currentFilterIndex
{
    self.currentFilterIndex = currentFilterIndex;
    [[QLRecordManager shareManager]changeFilter:filter];
}


//MARK:---------QLRecordManagerVCDelegate--------
-(void)recordFinishedWithOutputFileUrl:(NSURL *)fileUrl RecordTime:(CGFloat)recordTime
{
    if (recordTime < self.param.minTime) {
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"录制时长少于%fS,请重新录制!",self.param.minTime] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self cancleClick];
        }];
        [alter addAction:action];
        [self presentViewController:alter animated:YES completion:nil];
    }
    self.outputFileUrl = fileUrl;
}


//更新时间状态
-(void)reloadRecordTime:(CGFloat)time
{
//    self.recordTimeView.hidden = time > 0 ? NO : YES;
//    [self.recordTimeView reloadTime:(long)floorf(time)];

    self.recordView.timeView.hidden = time>0 ? NO:YES;
    self.recordView.timeView.timeLB.text = [NSString stringWithFormat:@"%02ld秒",(long)floorf(time)];
    [self.recordView.propgressView updateProgressWithValue:time/self.param.maxTime];
}

//闪光灯是否隐藏
-(void)lightIsHidden:(BOOL)isHidden
{
    self.topView.lightBtn.hidden = isHidden;
}

//添加视频采集
-(void)showPreviewView:(QLGPUImageView *)displayView
{
    [self.view addSubview:displayView];
    [self.view bringSubviewToFront:self.topView];
    [self.view bringSubviewToFront:self.recordView];
    [self.view bringSubviewToFront:self.optionsView];
//    [self.view bringSubviewToFront:self.recordTimeView];
}



//MARK:---------QLBottomOptionsViewDelegate------
-(void)selectedClick
{
    [self updateViewWithOptionsViewHidden:YES];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.param.getCurrentMode == videoMode) {//视频
            //保存视频
            [[QLRecordManager shareManager]saveVideo];
            [self.playerVC.view removeFromSuperview];
            [self.playerVC removeFromParentViewController];
            self.playerVC = nil;
            [self reloadRecordTime:0];
        }else{//照片
            [[QLRecordManager shareManager]savePhoto];
        }
        [self close];
    });
}


//-(void)pushEditPage{
//    NSLog(@"编辑滤镜界面");
//    NLFontEditViewController *editPage = [NLFontEditViewController new];
//    editPage.originalImage = [[NLRecordManager shareManager] getPhoto];
//    [self showViewController:editPage sender:nil];
//}


-(void)showPreviewVideo
{
    if (self.outputFileUrl) {
        self.playerVC = [QLVideoPlayer new];
        self.playerVC.model.videoURL = self.outputFileUrl;
        [self addChildViewController:self.playerVC];
        [self.view insertSubview:self.playerVC.view belowSubview:self.optionsView];
    }
}

-(void)cancleClick
{
    [self updateViewWithOptionsViewHidden:YES];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.param.getCurrentMode == videoMode) {//视频
            [self.playerVC.view removeFromSuperview];
            [self.playerVC removeFromParentViewController];
//            self.playerVC = nil;
            [self reloadRecordTime:0];
        }
        [self readyRecordVideo];
    });
}


//MARK:------QLSettingViewDelegate--------
-(void)closeSettingView
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//MARK:--------TZImgePickerControllerDelegate----------
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
//    NLFontEditViewController *editPage = [NLFontEditViewController new];
//    editPage.originalImage = photos.firstObject;
//    [self showViewController:editPage sender:nil];
    NSLog(@"拿到的图片==%@",photos.firstObject);

    
}


//MARK:---------lazy---------
-(QLSettingView*)settingView
{
    if (_settingView == nil) {
        _settingView = [[QLSettingView alloc]initWithFrame:CGRectMake(0, 0, QL_SELECTEDBTN_WIDTH, QL_SCREEN_HEIGHT)];
        _settingView.delegate = self;
    }
    return _settingView;
}



//相机的状态
-(void)checkCameraStatus
{
    __weak __typeof(&*self)weakSelf = self;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [self.view addSubview:self.settingView];
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [self checkCameraStatus];
                });
            }
        }];
    }else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        [self.view addSubview:self.settingView];
    }else{
        [self.settingView removeFromSuperview];
        [self configureView];
        [self readyRecordVideo];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
            [weakSelf checkAudioStatus];
        });
    }
}

//麦克风的状态
-(BOOL)checkAudioStatus
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        if (self.flag == 0) {
            UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"无法使用麦克风" message:@"您未开启麦克风,录制视频将没有声音" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action){
                [self close];
                self.flag = 0;
            }];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                self.flag = 0;
            }];
            [alter addAction:action];
            [alter addAction:action1];
            [self showViewController:alter sender:nil];
        }
        return NO;
    }else{
        return YES;
    }
}

-(void)trasitAnimation
{
    CATransition *animation = [CATransition animation];
    animation.type = kCATransitionFade;
    animation.duration = 0.7f;
    animation.subtype = kCATransitionFromRight;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:animation forKey:@"animation"];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.filterView.window) {
        self.recordView.hidden = NO;
        [self.filterView removeFromSuperview];
    }
}

-(void)dealloc
{
    NSLog(@"=====");
}





@end
